import { defineStore } from 'pinia'
import {RouteRecordModel} from "../router/route";

interface MenuMetaModel {
  title: string;
  name: string;
  fullPath: string;
  icon: string;
  children: MenuMetaModel[];
}

interface MenuStateModel {
  collapse: boolean;
  allMenus: MenuMetaModel[];
  menus: MenuMetaModel[];
  activeMenuName: string;
  openedMenuNames: string[];

  navMenus: MenuMetaModel[];
  activeNavMenuName: string;
}

const useMenuStore = defineStore('menu', {
  state: (): MenuStateModel => {
    return {
      collapse: false,
      allMenus: [],
      menus: [],
      activeMenuName: '',
      openedMenuNames: [],

      navMenus: [],
      activeNavMenuName: ''
    }
  },
  actions: {
    setCollapse(collapse: boolean) {
      this.collapse = collapse;
    },
    setAllMenus(menus: MenuMetaModel[]) {
      // console.log('setAllMenus', menus);
      this.allMenus = menus;
      if (!this.navMenus.length) {
        this.navMenus = menus.slice();
      }
      this.setMenus(menus);
    },
    setMenus(menus: MenuMetaModel[]) {
      this.menus = menus;
    },
    setActiveMenuName(name: string) {
      this.activeMenuName = name;
    },
    setOpenedMenuNames(names: string[]) {
      this.openedMenuNames = names;
    },

    setActiveNavMenuName(name: string) {
      this.activeNavMenuName = name;
    },
  }
});

function filterMenus(routes: RouteRecordModel[], parentFullPath = ''): MenuMetaModel[] {
  return (routes || []).reduce((prev, curr) => {
    if (curr.meta) { // 菜单
      const prefix = parentFullPath ? parentFullPath + '/' : '';
      const fullPath = prefix + curr.path;
      const item: MenuMetaModel = {
        title: curr.meta.title,
        name: (curr.meta.name || curr.name) as string,
        icon: curr.meta.icon,
        fullPath,
        children: curr.meta.isMenuGroup ? filterMenus(curr.children as RouteRecordModel[], fullPath) : []
      }
      prev.push(item);
    }
    return prev;
  }, [] as MenuMetaModel[])
}


export { useMenuStore, filterMenus, MenuMetaModel, MenuStateModel }
